import React, { useState, useEffect, useRef } from 'react'
import { Button, Radio, Table, message, Progress, Modal } from 'antd';
import { updateStatus, RemoteOpenLock, suoshekongzhi, suochongqi, tiaoshi, wanchengtiaoshi } from '../service';
import "../index.less"


const { confirm } = Modal
const MoreActron = ({ setIsModalOpen, UpdateList, ItemData }) => {


    const Btn = ["远程开锁", "松手牌", "缩锁舌", "重启此柜锁", "调试此柜锁"]

    const [value, setValue] = useState(1);



    const Acitcve = (item) => {
        let data = {
            "shichang": "10",
            "zhuangtai": "0",
            "source": 1,
            "guihao": ItemData.locker_number,
            "lockclass": ItemData.locker_type,
            "uuid": new Date().getTime().toString(),
        }
        switch (item) {
            case "远程开锁":
                console.log("远程开锁", ItemData)

                RemoteOpenLock(data).then(res => {
                    if (res.result == 0) {
                        message.success("开锁成功")
                    } else {
                        message.error("开锁失败 : " + res.msg)
                    }
                })
                break;
            case "松手牌":
                console.log("松手牌")
                suoshekongzhi({
                    ...data,
                    "suoshe": 3,
                    "shoupai": 1
                }).then(res => {
                    if (res.result == 0) {
                        message.success("操作成功")
                    } else {
                        message.error("操作失败 : " + res.msg)
                    }
                })
                break;
            case "缩锁舌":
                suoshekongzhi({
                    ...data,
                    "suoshe": 1,
                    "shoupai": 5
                }).then(res => {
                    if (res.result == 0) {
                        message.success("操作成功")
                    } else {
                        message.error("操作失败 : " + res.msg)
                    }
                })
                break;
            case "重启此柜锁":
                suochongqi({
                    "guihao": ItemData.locker_number,
                    "lockclass": ItemData.locker_type,
                    "uuid": new Date().getTime().toString(),
                }).then(res => {
                    if (res.result == 0) {
                        message.success("操作成功")
                    } else {
                        message.error("操作失败 : " + res.msg)
                    }
                })
                break;
            case "调试此柜锁":



                tiaoshi(data).then(res => {
                    if (res.result == 0) {
                        message.success("操作成功")

                        setVisible(true)
                    } else {
                        message.error("操作失败 : " + res.msg)

                    }
                })
                break;

        }
    }

    const ok = () => {
        console.log(value)

        updateStatus(ItemData.id, { usage_status: value }).then(res => {
            if (res.code == 0) {
                message.success("操作成功")
                setIsModalOpen(false)
                UpdateList(1)
            }
        })
    };

    const [visible, setVisible] = useState(false);


    return (
        <div>
            <div className='Title ' >柜锁操作</div>
            {
                Btn.map((item, index) => {
                    return (
                        <Button type='primary' style={{ marginRight: 9, marginTop: 10 }} onClick={() => Acitcve(item)} key={index}>{item}</Button>
                    )

                })
            }

            <div className='Title' style={{ marginTop: 20 }}>状态变更</div>

            <Radio.Group value={value} onChange={e => setValue(e.target.value)} style={{ marginRight: 9, marginTop: 6 }}>
                <Radio disabled={ItemData.usage_status == 0} value={0}>空闲</Radio>
                <Radio disabled={ItemData.usage_status == 6} value={6} >维修</Radio>
                <Radio disabled={ItemData.usage_status == 8} value={8}>脏柜</Radio>
            </Radio.Group>
            <Open lock={ItemData.locker_number} visible={visible} setVisible={setVisible} />
            <div style={{ marginTop: 15 }} onClick={ok}><Button type='primary'>确定</Button></div>
        </div>
    )
}

export default MoreActron



const Open = ({ visible, setVisible, lock }) => {
    const timerRef = useRef(null);
    const [left, setLeft] = useState(12_000);   // 剩余毫秒
    const total = 12_000;
    const [List, setList] = useState([])
    const REG = /^\[(.*?)\s+(\d{2}:\d{2}:\d{2})\]\s*\[(\d{8})\]\s*\[([^[\]]+)\]\s*(.+)$/;
    useEffect(() => {
        if (!visible) return;          // 弹窗关闭不跑
        setLeft(total);                // 每次打开重置
        timerRef.current = setInterval(() => {
            setLeft((l) => {
                const next = l - 1_000;
                if (next <= 0) {
                    clearInterval(timerRef.current);
                    wanchengtiaoshi().then(res => {
                        console.log(res)
                        console.log(res.msg)
                        setList(parseLog(res.msg))

                        console.log("结果", parseLog(res.msg))
                    })

                }
                return next;
            });
        }, 1_000);

        return () => clearInterval(timerRef.current);
    }, [visible]);

    const pct = Math.round((left / total) * 100);
    const twoColors = { '0%': '#108ee9', '100%': '#87d068' };


    function parseLog(raw) {
        return raw
            .split(/\r?\n/)                // 拆行
            .map(l => l.trim())
            .filter(Boolean)               // 去掉空行
            .map(line => {
                const m = line.match(REG);
                if (!m) return null;
                const [, date, time, seq, source, content] = m;
                return { date, time, seq, source, content };
            })
            .filter(Boolean);              // 去掉不匹配的行
    }
    return (
        <Modal
            title={lock + "调试结果"}
            visible={visible}
            width={900}

            footer={null}
            onCancel={() => setVisible(false)}
        >

            <div style={{ width: '100%', textAlign: 'center', margin: '30px 0' }}>

                {
                    left / 1000 > 0 ? <div style={{ transform: 'scale(1.5)', }}>
                        <Progress
                            type="circle"
                            percent={pct}
                            strokeColor={twoColors}
                            format={() => <span style={{ fontSize: 32 }}>{Math.ceil(left / 1000)} <br /><span style={{ fontSize: 12 }}>秒后查看结果</span></span>}
                        />
                    </div> : <Table
                        rowKey={(r, i) => i}
                        size="small"
                        pagination={false}
                        columns={[
                            { title: '时间', dataIndex: 'time', width: 90 },
                            { title: '控制器ID', dataIndex: 'seq', width: 110 },
                            { title: '来源', dataIndex: 'source', width: 120 },
                            { title: '结果', dataIndex: 'content' },
                        ]}
                        dataSource={List}
                    />
                }



            </div>


        </Modal>
    );
}